package com.hui.controller;

import com.hui.utils.FastDFSUtil;
import com.hui.utils.UploadUtil;
import com.hui.vo.FilesUploadVo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/08/31/10:14
 * @Description:
 */
@RestController
public class FilesUploadController {
    @Autowired
    private FastDFSUtil fastDFSUtil;

    @Autowired
    private UploadUtil uploadUtil;

    @Autowired
    private Redisson redisson;

    @RequestMapping("/filesUpload")
    public List<FilesUploadVo> filesUpload(MultipartFile[] files) {
        // 获取分布式锁，底层源码就是集成了setnx，过期时间等操作
        RLock lock = redisson.getLock("hui");
        // 上锁，30秒
        lock.lock(30, TimeUnit.SECONDS);
        List<FilesUploadVo> list = null;
        try {
            /* 1.上传到web服务器 */
            List<Map<String, String>> messageList = uploadUtil.webUpload(files);
            /* 2.上传到FastDFS服务器 */
            list = fastDFSUtil.fastDfsUpload(messageList);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
        }
        return list;
    }

    // 创建Redisson并放入IOC容器
    @Bean
    public Redisson redisson() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://47.115.139.213:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }
}
